package com.google.gwt.hmconsole.server;

import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.FilterHolder;
import org.mortbay.jetty.webapp.WebAppContext;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class HostedModeConsoleServer {

  public static final String HOSTED_MODE_STATE = "hosted-mode-state";
  private final int port;
  private Server jetty = null;
  private final HostedModeState hostedModeState;

  public void join() {
    try {
      jetty.join();
    } catch (Exception e) {
      throw new HostedModeConsoleException(e.getMessage(), e);
    }
  }

  public HostedModeConsoleServer(int port, HostedModeState hostedModeState) {
    this.port = port;
    this.hostedModeState = hostedModeState;
  }

  public void start() {
    try {
      jetty = new Server(this.port);
      // TODO: Un-hard-code the path
      URL warURL = new File(
          "/home/uga/Projects/workspaces/gwt/gwt-hm-console/war").toURI().toURL();
      WebAppContext webAppContext = new WebAppContext(warURL.toExternalForm(),
          "/");
      webAppContext.addFilter(new FilterHolder(new Filter() {

        public void init(FilterConfig filterConfig) throws ServletException {
        }

        public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
          request.setAttribute(HOSTED_MODE_STATE,
              HostedModeConsoleServer.this.hostedModeState);
          chain.doFilter(request, response);
        }

        public void destroy() {
        }
      }), "/*", Handler.DEFAULT);
      jetty.setHandler(webAppContext);
      jetty.start();
    } catch (Exception e) {
      throw new HostedModeConsoleException(e.getMessage(), e);
    }
  }

}
